<?php
/**
 * CreateUser: zlh
 * CreateTime: 2022/1/21 18:18
 * Remark:
 */

namespace App\Models\Department;

use App\Consts\BaseConsts\BaseConsts;
use App\Consts\TableConsts\TableConsts;
use App\Models\BaseModel;
use App\Models\BaseModelV2;

class DepartmentModel extends BaseModelV2
{
    protected $table = TableConsts::CY_DEPARTMENT_TABLE_NAME;

    protected $primaryKey = TableConsts::CY_DEPARTMENT_TABLE_PRIMARY_KEY;

    protected $attributes = [
        'status' => BaseConsts::STATUS_NORMAL,
    ];

    protected $fillable = [
        'department_id',
        'company_id',
        'department_name',
        'department_parent_id',
        'department_level',
        'department_principal_id',
        'status',
        'created_at',
        'updated_at',
    ];

    /**
     * 不需要走全局作用域
     */
    protected static function booted(){}

    public function isExistByCondition($conditionData){
        return $this
            ->withoutGlobalScopes()
            ->firstOrnew($conditionData)->exists;
    }

    /**
     * 新增部门
     * @return bool
     */
    public function addDepartmentModel($departmentData): bool
    {
        return $this->save($departmentData);
    }

    /**
     * 编辑部门
     * @param $departmentData
     * @return bool
     */
    public function editDepartmentEdit($departmentData): bool
    {
        return $this->where('department_id',$departmentData['department_id'])
            ->update($departmentData);
    }

    /**
     *  获取部门详情
     * @param $departmentId
     * @param array|string[] $select
     * @return mixed
     */
    public function getDepartmentInfoByDepartmentIdModel($departmentId, array $select = ["*"]): mixed
    {
        return $this
            ->select($select)
            ->find($departmentId);
    }

    /**
     * 通过部门名字获取部门信息
     * @param string $departmentName
     * @param string $select
     * @return mixed
     */
    public function getDepartmentInfoModelByDepartmentName(string $departmentName, array $select = ["*"]): mixed
    {
        return $this->select($select)
            ->where('department_name',$departmentName)
            ->first();
    }


    /**
     * 通过公司ID获取部门菜单
     * @param $companyId
     * @return mixed
     */
    public function getDepartmentMenuByCompanyId($companyId,$select = ['*']): mixed
    {
        return $this->select($select)
            ->where('company_id',$companyId)
            ->where('status',BaseConsts::STATUS_NORMAL)
            ->get();
    }

    /**
     * 通过公司获取部门列表
     * @param $query
     * @param $pageSize
     * @return mixed
     */
    public function getDepartmentListByCompanyId($query,$pageSize): mixed
    {
        return $query->Paginate($pageSize);
    }

    public function getDeptCompanyIdByDeptId($departmentId)
    {
        return $this
            ->withoutGlobalScopes()
            ->select("company_id")
            ->where('department_id',$departmentId)
            ->first();
    }

}